﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivaScriptConv
{
    class PvFieldFactory
    {
        // pv_000.field.00.stage=XXX
        private string DataPath;
        private Dictionary<string, Dictionary<int, string>> DataStorage;

        public PvFieldFactory(string path)
        {
            DataPath = path;
            ParseProp();
        }

        private void ParseProp()
        {
            DataStorage = new Dictionary<string, Dictionary<int, string>>();
            foreach (var row in File.ReadAllLines(DataPath))
            {
                if (string.IsNullOrEmpty(row) == false && !row.StartsWith("#"))
                {
                    var d = row.Split("=".ToCharArray());
                    var h = d[0].Split(".".ToCharArray());
                    if (h.Length < 4 || !h[1].Equals("field") || !h[3].Equals("stage")) continue;
                    var k = h[0];
                    Dictionary<int, string> s;
                    if (DataStorage.ContainsKey(k))
                    {
                        s = DataStorage[k];
                    }
                    else
                    {
                        s = new Dictionary<int, string>();
                        DataStorage.Add(k, s);
                    }
                    var i = 0;
                    if (Int32.TryParse(h[2], out i))
                    {
                        if (!s.ContainsKey(i) && d.Length > 1 && !String.IsNullOrEmpty(d[1]))
                            s.Add(i, d[1]);
                    }
                }
            }
        }

        public string GetStageName(string pvName, int index)
        {
            if (DataStorage.ContainsKey(pvName))
            {
                var d = DataStorage[pvName];
                if (d != null && d.ContainsKey(index))
                    return d[index];
                else return String.Empty;
            }
            else return String.Empty;
        }
    }
}
